package com.banshuibao.bsb_android.util;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.media.AudioFormat;
import android.media.AudioRecord;
import android.media.MediaRecorder;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.Settings;

import com.banshuibao.bsb_android.MyApplication;

import java.io.File;
import java.io.IOException;

/**
 * Created by zyh on 2017/11/27.
 */

public class RecorderUtil {

// 录音

    private MediaRecorder recorder;

    private Boolean bool = false;

    private String path;

    private Activity context;

    private static final int REQUEST_EXTERNAL_STORAGE = 10000;
    private static String[] PERMISSIONS_STORAGE = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE
    };

    public RecorderUtil(Activity context) {
        this.context = context;
    }

    //初始化

    private void init() {

        recorder.setAudioSource(MediaRecorder.AudioSource.MIC); // 音频输入源

        recorder.setOutputFormat(MediaRecorder.OutputFormat.AMR_NB);    //设置输出格式

        recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);    //设置编码格式

        path = getDirDownloadPath() + "/adio.amr";

        recorder.setOutputFile(path);    //设置音频保存路径

    }

    /**
     * 开始录制音频
     */

    public void startRecord() {
        if (recorder == null) {

            recorder = new MediaRecorder();

            this.init();

        }

        if (bool == false) {

            try {

                recorder.prepare();

                recorder.start(); // 开始录制

                XToast.showToast(MyApplication.applicationInstance.getApplicationContext(), "开始录音");

                bool = true;

            } catch (IOException e) {
                XToast.showToast(MyApplication.applicationInstance.getApplicationContext(),"请开启读写存储权根");
            }

        } else if (bool) {

            XToast.showToast(MyApplication.applicationInstance.getApplicationContext(), "当前正在录音");

        }

    }

    /**
     * 停止录制，资源释放
     */

    public void stopRecord() {

        if (recorder != null) {
            recorder.stop();

            recorder.release();

            recorder = null;

            XToast.showToast(MyApplication.applicationInstance.getApplicationContext(), "文件已保存");

            bool = false;

            MyApplication.applicationInstance.getApplicationContext().sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + Environment.getExternalStorageDirectory())));
        }

    }

    public boolean getBool() {
        return bool;
    }

    public String getDirDownloadPath() {
        if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            return "";
        }
        String dir = Environment.getExternalStorageDirectory().getPath() + "/";
        File file = new File(dir + "/jsb_audio");
        if (!file.exists())
            file.mkdir();
        return file.getPath();
    }


    // 音频获取源
    public static int audioSource = MediaRecorder.AudioSource.MIC;
    // 设置音频采样率，44100是目前的标准，但是某些设备仍然支持22050，16000，11025
    public static int sampleRateInHz = 44100;
    // 设置音频的录制的声道CHANNEL_IN_STEREO为双声道，CHANNEL_CONFIGURATION_MONO为单声道
    public static int channelConfig = AudioFormat.CHANNEL_IN_STEREO;
    // 音频数据格式:PCM 16位每个样本。保证设备支持。PCM 8位每个样本。不一定能得到设备支持。
    public static int audioFormat = AudioFormat.ENCODING_PCM_16BIT;
    // 缓冲区字节大小
    public static int bufferSizeInBytes = 0;
    /**
     * 判断是是否有录音权限
     */
    public static boolean isHasPermission(){
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            return  true;
        }
        bufferSizeInBytes = 0;
        bufferSizeInBytes = AudioRecord.getMinBufferSize(sampleRateInHz,
                channelConfig, audioFormat);
        AudioRecord audioRecord =  new AudioRecord(audioSource, sampleRateInHz,
                channelConfig, audioFormat, bufferSizeInBytes);
        //开始录制音频
        try{
            // 防止某些手机崩溃，例如联想
            audioRecord.startRecording();
        }catch (IllegalStateException e){
            e.printStackTrace();
        }
        /**
         * 根据开始录音判断是否有录音权限
         */
        if (audioRecord.getRecordingState() != AudioRecord.RECORDSTATE_RECORDING) {
            return false;
        }
        audioRecord.stop();
        audioRecord.release();
        audioRecord = null;

        return true;
    }


    public  void AskForPermission() {
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setTitle("需要手动打开相关权限!");
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

            }
        });
        builder.setPositiveButton("设置", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                intent.setData(Uri.parse("package:" + context.getPackageName())); // 根据包名打开对应的设置界面
                context.startActivity(intent);
            }
        });
        builder.create().show();
    }

}
